package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.minio.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author jack
 * @data 2024 9:23
 */
@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 素材上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1. 参数校验
        if (multipartFile == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        //2. 将前端传过来的图片上传到minio
        String originalFilename = multipartFile.getOriginalFilename();      //a.b.png
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        String targetFileName = name + suffix;

        InputStream is = null;
        try {
             is = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String imgUrl = fileStorageService.uploadImgFile("", targetFileName, is);
        //3. 将minio返回的图片的url封装成WmMaterial对象，并存入wm_material表中
        WmMaterial material = WmMaterial
                .builder()
                .url(imgUrl)
                .type((short)0)
                .isCollection((short)0)
                .createdTime(new Date())
                .userId(WmThreadLocalUtil.getUser().getId())
                .build();
        save(material);

        //4. 将WmMaterial对象返回给前端
        return ResponseResult.okResult(material);
    }

    /**
     * 素材列表
     *
     * @param materialDto
     * @return
     */
    @Override
    public ResponseResult queryByPage(WmMaterialDto materialDto) {
        //1. 参数校验
        if (materialDto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        materialDto.checkParam();

        //2. 创建分页对象：Page
        Page page = new Page(materialDto.getPage(),materialDto.getSize());

        //3. 创建条件对象：Wrapper
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(StringUtils.isNotBlank(materialDto.getIsCollection()) && "1".equals(materialDto.getIsCollection()),
                        WmMaterial::getIsCollection, materialDto.getIsCollection())
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmMaterial::getCreatedTime);

        //4. 分页条件查询
        page(page,wrapper);

        //5. 封装结果返回
        PageResponseResult result = new PageResponseResult((int)page.getCurrent(),(int) page.getSize(),(int) page.getTotal());
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(),page.getRecords(),AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }
}
